package com.example.backend.component;

import com.example.backend.security.SecurityUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

@Component
public class JwtTokenUtil {

    // 令牌类型常量
    private static final String TOKEN_TYPE_ACCESS = "ACCESS";
    private static final String TOKEN_TYPE_REFRESH = "REFRESH";

    @Value("${jwt.secret:7gT+9KqXrLpZzVnQfWmN0jJcEaYsUkPwBdRiFhVxLtM=}")
    private String secret;

    @Value("${jwt.accessToken.expiration:3600}")  // 访问令牌默认1小时
    private Long accessTokenExpiration;

    @Value("${jwt.refreshToken.expiration:604800}") // 刷新令牌默认7天
    private Long refreshTokenExpiration;

    @Value("${jwt.token.version:1}")
    private Integer tokenVersion;

    private SecretKey getSigningKey() {
        return Keys.hmacShaKeyFor(secret.getBytes());
    }

    // ========== 基础令牌生成方法 ==========

    // 生成访问令牌（带自定义数据）
    public String generateAccessToken(SecurityUser userDetails, Map<String, Object> customClaims) {
        return buildToken(userDetails.getUsername(), TOKEN_TYPE_ACCESS, accessTokenExpiration, customClaims);
    }

    /**
     * 生成刷新令牌（带自定义数据）
     */
    public String generateRefreshToken(SecurityUser userDetails, Map<String, Object> customClaims) {
        return buildToken(userDetails.getUsername(), TOKEN_TYPE_REFRESH, refreshTokenExpiration, customClaims);
    }

    /**
     * 生成访问令牌（无自定义数据）
     */

    public String generateAccessToken(SecurityUser userDetails) {
        return generateAccessToken(userDetails, new HashMap<>());
    }

    // 生成刷新令牌（无自定义数据）
    public String generateRefreshToken(SecurityUser userDetails) {
        return generateRefreshToken(userDetails, new HashMap<>());
    }

    // ========== 自定义数据令牌生成方法 ==========

    // 生成完全自定义的令牌（高级用法）
    public String generateCustomToken(String subject, String tokenType, long expirationSeconds,
                                      Map<String, Object> customClaims) {
        return buildToken(subject, tokenType, expirationSeconds, customClaims);
    }

    // ========== 核心构建方法 ==========

    private String buildToken(String subject, String tokenType, long expirationSeconds,
                              Map<String, Object> customClaims) {
        // 合并系统声明和自定义声明
        Map<String, Object> claims = new HashMap<>(customClaims);
        claims.put("version", tokenVersion);
        claims.put("tokenType", tokenType);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + expirationSeconds * 1000))
                .signWith(getSigningKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    // ========== 令牌解析方法 ==========

    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    public Integer getVersionFromToken(String token) {
        return getClaimFromToken(token, claims -> claims.get("version", Integer.class));
    }

    public String getTokenTypeFromToken(String token) {
        return getClaimFromToken(token, claims -> claims.get("tokenType", String.class));
    }

    // 获取自定义声明值
    public <T> T getCustomClaim(String token, String claimName, Class<T> claimType) {
        return getClaimFromToken(token, claims -> claims.get(claimName, claimType));
    }

    // 获取所有声明（包括自定义声明）
    public Map<String, Object> getAllClaims(String token) {
        return new HashMap<>(getAllClaimsFromToken(token));
    }

    // ========== 通用工具方法 ==========

    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    private Claims getAllClaimsFromToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(getSigningKey())
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    private Boolean isTokenVersionValid(String token) {
        final Integer version = getVersionFromToken(token);
        return version != null && version.equals(tokenVersion);
    }

    // ========== 令牌验证方法 ==========

    public Boolean validateAccessToken(String token, UserDetails userDetails) {
        try {
            final String username = getUsernameFromToken(token);
            final String tokenType = getTokenTypeFromToken(token);

            return (username.equals(userDetails.getUsername())
                    && TOKEN_TYPE_ACCESS.equals(tokenType)
                    && !isTokenExpired(token)
                    && isTokenVersionValid(token));
        } catch (JwtException | IllegalArgumentException e) {
            return false;
        }
    }

    public Boolean validateRefreshToken(String token, UserDetails userDetails) {
        try {
            final String username = getUsernameFromToken(token);
            final String tokenType = getTokenTypeFromToken(token);

            return (username.equals(userDetails.getUsername())
                    && TOKEN_TYPE_REFRESH.equals(tokenType)
                    && !isTokenExpired(token)
                    && isTokenVersionValid(token));
        } catch (JwtException | IllegalArgumentException e) {
            return false;
        }
    }

    /**
     * 验证令牌是否有效
     */
    public Boolean isJwtValid(String token) {
        try {
            getAllClaimsFromToken(token);
            return !isTokenExpired(token) && isTokenVersionValid(token);
        } catch (JwtException | IllegalArgumentException e) {
            return false;
        }
    }

    // ========== 令牌刷新方法 ==========

    public String refreshAccessTokenWithRefreshToken(String refreshToken) {
        if (!validateRefreshTokenType(refreshToken)) {
            throw new JwtException("Invalid refresh token type");
        }

        final Claims claims = getAllClaimsFromToken(refreshToken);
        claims.setIssuedAt(new Date());
        claims.setExpiration(new Date(System.currentTimeMillis() + accessTokenExpiration * 1000));
        claims.put("tokenType", TOKEN_TYPE_ACCESS);

        // 保留所有自定义声明
        return Jwts.builder()
                .setClaims(claims)
                .signWith(getSigningKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    // 刷新令牌并更新自定义数据
    public String refreshAccessTokenWithCustomClaims(String refreshToken, Map<String, Object> updatedClaims) {
        if (!validateRefreshTokenType(refreshToken)) {
            throw new JwtException("Invalid refresh token type");
        }

        final Claims claims = getAllClaimsFromToken(refreshToken);
        claims.setIssuedAt(new Date());
        claims.setExpiration(new Date(System.currentTimeMillis() + accessTokenExpiration * 1000));
        claims.put("tokenType", TOKEN_TYPE_ACCESS);

        // 更新自定义声明
        updatedClaims.forEach(claims::put);

        return Jwts.builder()
                .setClaims(claims)
                .signWith(getSigningKey(), SignatureAlgorithm.HS256)
                .compact();
    }

    private Boolean validateRefreshTokenType(String token) {
        final String tokenType = getTokenTypeFromToken(token);
        return TOKEN_TYPE_REFRESH.equals(tokenType);
    }

    // ========== 系统管理方法 ==========

    public void upgradeTokenVersion() {
        this.tokenVersion++;
    }

    public int getCurrentTokenVersion() {
        return this.tokenVersion;
    }
}